<template>
	<view class="container">
		<z-paging refresher-only ref="paging" @onRefresh="getCartList" safe-area-inset-bottom
			:loading-more-enabled="false">
			<template #top>
				<customNavbar @delClick="deleteSelectedItems" :selectedIdsArray="selectedIdsArray"></customNavbar>
			</template>
			<loading :height="emptyHeight" v-if="isLoading"></loading>
			<empty v-if="dataList.length === 0 && !isLoading" :height="systemStore.isPersonalization?300:emptyHeight"
				text="购物车为空"></empty>
			<view class="main" :style="{paddingBottom:dataList.length || !systemStore.isPersonalization ?0:50 + 'px'}">
				<view class="list-box" v-if="dataList.length && !isLoading">
					<uv-checkbox-group v-model="selectedIdsArray">
						<uni-swipe-action>
							<view class="li" v-for="(item,index) in dataList" :key="item.id"
								@click="navigateTo(`/subPackages/product/detail?product_id=${item.product_id}`)">
								<uni-swipe-action-item :right-options="options"
									@click="swipeActionClick($event,item.product.id, item.productSpec.id)">
									<view class="li-main u-flex">
										<uv-checkbox :customStyle="{marginLeft: '30rpx'}" active-color="#000000"
											:name="item.id" :checked="cartStore.selectedIds.has(item.id)"
											@change="toggleSelectItem(item.id)"></uv-checkbox>
										<view class="li-right u-flex">
											<zero-lazy-load :height="160" imgMode='aspectFill'
												:image="item.product.cover_image" class="img"
												:borderRadius="4"></zero-lazy-load>
											<view class="li-content u-flex-col u-flex-between u-col-start">
												<view>
													<view class="li-name">{{item.product.name}}</view>
													<view class="spec">{{item.productSpec.spec_name}}</view>
												</view>
												<view class="li-footer u-flex-between">
													<view class="li-price">
														<span class="price">
															<span class="price-icon">￥</span>
															<span class="price-text">{{item.productSpec.price}}</span>
														</span>
														<span
															class="origin-price">￥{{item.productSpec.original_price}}</span>
													</view>
													<view class="number u-flex">
														<uv-icon name="minus" size="15"
															@click="minusChange(item)"></uv-icon>
														<span class="number-text">{{item.number}}</span>
														<uv-icon name="plus" size="14" color="#000000"
															@click="plusChange(item)"></uv-icon>
													</view>
												</view>
											</view>
										</view>
									</view>
								</uni-swipe-action-item>
								<view class="li-subtotal">
									<span class="subtotal-text">小计：</span>
									<span class="subtotal-price">
										<span class="price-icon">￥</span>
										<span class="price-text">{{getSubtotal(item)}}</span>
									</span>
								</view>
							</view>
						</uni-swipe-action>
					</uv-checkbox-group>
				</view>
				<!-- 推荐列表 -->
				<recommendation-list v-if="!isLoading"></recommendation-list>
				<view class="safe-area-inset-bottom"></view>
			</view>
			<template #bottom>
				<view class="footer" v-if="dataList.length && !isLoading">
					<view class="footer-content u-flex-between">
						<view class="select u-flex" @click="toggleSelectAll">
							<span class="box u-flex-center">
								<uv-icon name="checkmark" size="16" color="#000000" v-if="isAllSelected"></uv-icon>
							</span>
							<span class="text">全选</span>
						</view>
						<view class="footer-right u-flex">
							<view>
								<span class="total">合计：</span>
								<span class="price-icon">￥</span>
								<span class="total-text">{{totalPrice}}</span>
							</view>
							<uv-button text="结算" color="#000000" :customStyle="{width:'168rpx',height:'72rpx'}"
								@click="submit"></uv-button>
						</view>
					</view>
					<view class="safe-area-inset"></view>
				</view>
			</template>
		</z-paging>
		<tabbar class="tabbar" :current="3"></tabbar>
	</view>
</template>

<script setup>
	import customNavbar from './components/custom-navbar.vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { computed, ref } from 'vue';
	import { apiGetShopCartList } from '@/api/shopping-cart.js'
	import { collection } from '@/api/product.js'
	import { getNavbarHeight } from '@/utils/system.js'
	import useCartStore from '@/store/modules/cart.js'
	import { waitForAppLaunch, showToast, showModal } from '@/utils/common.js'
	import eventBus from '@/utils/eventBus.js'
	import useSystemStore from '@/store/modules/system.js'
	import { navigateTo } from '@/utils/router.js'

	const systemStore = useSystemStore();
	const cartStore = useCartStore()
	const { windowHeight } = wx.getWindowInfo()
	const emptyHeight = computed(() => windowHeight - getNavbarHeight() - 50)

	const options = [{
			text: '移至收藏',
			style: {
				fontSize: "24rpx",
				backgroundColor: '#F8BC38'
			}
		},
		{
			text: '删除',
			style: {
				fontSize: "24rpx",
				backgroundColor: '#f12a34'
			}
		}
	]

	const isLoading = ref(true)
	const paging = ref(null)

	onLoad(async () => {
		// #ifndef MP-WEIXIN
		uni.hideTabBar();
		// #endif
		await waitForAppLaunch()
		getCartList()
	})


	// 购物车列表
	const dataList = computed(() => cartStore.list);
	// 计算小计
	const getSubtotal = computed(() => cartStore.getSubtotal);
	// 获取总价
	const totalPrice = computed(() => cartStore.totalPrice);
	// 是否全选
	const isAllSelected = computed(() => cartStore.isAllSelected);
	// 将 Set 转换为数组的计算属性 => 当前选中的id
	const selectedIdsArray = computed({
		get() {
			return Array.from(cartStore.selectedIds);
		},
		set(value) {
			// 当复选框组的值变化时，更新 store 中的选中状态
			cartStore.selectedIds = new Set(value);
		}
	});

	// 使用 store 的 action 来修改数量
	const minusChange = (item) => {
		cartStore.minusChange(item);
	};

	const plusChange = (item) => {
		cartStore.plusChange(item);
	};

	// 切换单个商品选中状态
	const toggleSelectItem = (itemId) => {
		cartStore.toggleSelectItem(itemId);
	};

	// 全选/取消全选
	const toggleSelectAll = () => {
		cartStore.toggleSelectAll(isAllSelected.value);
	};

	// 滑动点击事件
	const swipeActionClick = ({ index }, productId, specId) => {
		if (index === 0) {
			// 移至收藏
			collectionChange(productId)
		} else {
			// 删除
			deleteItem(productId, specId)
		}
	}

	// 删除单个商品
	const deleteItem = async (productId, specId) => {
		uni.showLoading({
			title: '加载中...'
		})
		try {
			await cartStore.deleteItem(productId, specId);
			showToast('删除成功')
		} catch (error) {
			showToast(error.message || '删除失败，请重试')
		}
	};

	// 移至收藏
	const collectionChange = async (product_id) => {
		uni.showLoading({
			title: '加载中...'
		})
		try {
			const data = await collection({ product_id });
			showToast(data.msg)
		} catch (error) {
			showToast(error.message || '收藏失败，请重试')
		}
	};

	// 批量删除商品
	const deleteSelectedItems = async () => {
		// 检查是否有选中项
		if (cartStore.selectedIds.size === 0) {
			return showToast('请先选择商品');
		}
		try {
			// 显示确认对话框
			const { confirm } = await showModal(
				`确定要删除选中的 ${cartStore.selectedIds.size} 个商品吗？`,
				true,
				'确认删除'
			);
			// 用户取消则直接返回
			if (!confirm) return;
			// 执行删除操作
			await cartStore.deleteSelectedItems();
			showToast('删除成功');
		} catch (error) {
			// 统一错误处理
			console.error('删除过程中出现错误:', error);
			showToast(error.message || '删除失败');
		}
	};

	// 获取购物车列表
	const getCartList = async () => {
		try {
			await cartStore.getShopCartList()
			cartStore.initSelectedIds(); // 初始化选中状态
		} finally {
			isLoading.value = false
			if (!paging.value) return;
			paging.value.complete();
		}
	}

	// 结算
	const submit = () => {
		if (cartStore.selectedIds.size === 0) {
			return showToast('请先选择商品');
		}
		const selectedIdsArray = Array.from(cartStore.selectedIds);
		navigateTo(`/subPackages/create-order/index?type=2&buy_type=2&shop_cart_ids=${selectedIdsArray.join(',')}`);
	}

	// 监听登录成功事件
	eventBus.value.on('getCartList', () => {
		getCartList();
	});
</script>

<style>
	page {
		background-color: #F9F9F9;
	}
</style>
<style lang="scss" scoped>
	.container {
		.main {

			.list-box {
				padding: 0 28rpx;

				.li {
					width: 100%;
					margin-top: 20rpx;
					padding: 40rpx 0 20rpx;
					background-color: $base-color-white;
					border-radius: 12rpx;

					::v-deep .uni-swipe_button {
						width: 120rpx;
						padding: 0;
					}

					.li-main {

						.li-right {
							flex: 1;
							padding-left: 18rpx;

							.img {
								width: 160rpx;
								height: 160rpx;
								display: block;
							}

							.li-content {
								height: 160rpx;
								flex: 1;
								padding: 0 20rpx;

								.li-name {
									font-family: Source Han Sans CN, Source Han Sans CN;
									font-weight: 500;
									font-size: $font-size-30;
									color: $base-color;
									display: -webkit-box;
									-webkit-box-orient: vertical;
									-webkit-line-clamp: 1;
									overflow: hidden;
								}

								.spec {
									font-family: Source Han Sans CN, Source Han Sans CN;
									font-weight: 400;
									font-size: $font-size-24;
									color: $base-light-color;
									padding-top: 16rpx;
								}

								.li-footer {
									width: 100%;

									.li-price {
										.price {

											.price-icon {
												font-family: Source Han Sans CN, Source Han Sans CN;
												font-weight: 500;
												font-size: $font-size-20;
												color: $base-price-color;
											}

											.price-text {
												font-family: Source Han Sans CN, Source Han Sans CN;
												font-weight: 500;
												font-size: $font-size-30;
												color: $base-price-color;
											}
										}

										.origin-price {
											font-family: Source Han Sans CN, Source Han Sans CN;
											font-weight: 400;
											font-size: $font-size-20;
											color: $base-light-color;
											text-decoration: line-through;
											padding-left: 20rpx;
										}
									}

									.number {
										.number-text {
											width: 40rpx;
											margin: 0 15rpx;
											text-align: center;
										}
									}
								}
							}
						}
					}

					.li-subtotal {
						margin-top: 20rpx;
						padding: 20rpx 20rpx 0 0;
						border-top: 2rpx solid #ECECEC;
						text-align: right;

						.subtotal-text {
							font-family: Source Han Sans CN, Source Han Sans CN;
							font-weight: 400;
							font-size: $font-size-24;
							color: #666666;
						}

						.subtotal-price {

							.price-icon {
								font-family: Source Han Sans CN, Source Han Sans CN;
								font-weight: 500;
								font-size: $font-size-20;
								color: $base-price-color;
							}

							.price-text {
								font-family: Source Han Sans CN, Source Han Sans CN;
								font-weight: 500;
								font-size: $font-size-28;
								color: $base-price-color;
							}
						}
					}
				}
			}
		}

		.footer {
			padding: 30rpx 28rpx;
			width: 100%;
			background-color: $base-color-white;

			.footer-content {

				.select {
					.box {
						width: 36rpx;
						height: 36rpx;
						border-radius: 50%;
						border: 2rpx solid $base-color;
					}

					.text {
						padding-left: 20rpx;
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 400;
						font-size: $font-size-24;
						color: $base-color;
					}
				}

				.footer-right {
					.total {
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 400;
						font-size: $font-size-24;
						color: $base-color;
					}

					.price-icon {
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: bolder;
						font-size: $font-size-20;
						color: $base-price-color;
					}

					.total-text {
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: bolder;
						font-size: $font-size-36;
						color: $base-price-color;
						padding-right: 20rpx;
					}
				}
			}

			.safe-area-inset {
				height: 50px;
			}
		}
	}
</style>